package org.jeecg.modules.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.constant.CommonCuckoo;
import org.jeecg.common.util.RedisUtil;

import org.jeecg.cuckoo.enums.PaymentMethodEnum;
import org.jeecg.cuckoo.enums.PaymentStatusEnum;
import org.jeecg.cuckoo.enums.TransactionStatusEnum;
import org.jeecg.cuckoo.enums.TransactionTypeEnum;
import org.jeecg.modules.entity.*;
import org.jeecg.modules.mapper.CuVipCardMapper;
import org.jeecg.modules.payment.PaymentUtil;
import org.jeecg.modules.payment.enums.CuDeviceTypeEnum;
import org.jeecg.modules.payment.enums.CuPaymentMethodEnum;
import org.jeecg.modules.payment.enums.CuPaymentPlatformEnum;
import org.jeecg.modules.payment.vo.PaymentResponse;
import org.jeecg.modules.service.*;
import org.jeecg.modules.utils.GeneralToolsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;

/**
 * @Description: 会员卡卷
 * @Author: jeecg-boot
 * @Date: 2024-07-17
 * @Version: V1.0
 */
@Service
public class CuVipCardServiceImpl extends ServiceImpl<CuVipCardMapper, CuVipCard> implements ICuVipCardService {

    private String key = "vip:";
    private String redlist = key + "list";


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICuPaymentOrdersService paymentOrdersService;

    @Autowired
    private ICuUserDetailsService userDetailsService;

    @Autowired
    private ICuWalletaMnagementService walletaMnagementService;



    @Override
    public List<CuVipCard> vipList() {
        List<CuVipCard> list = (List<CuVipCard>) redisUtil.get(redlist);
        if (ObjectUtil.isNotEmpty(list)) {
            return list;
        }

        CuVipCard vipCard = new CuVipCard();
        vipCard.setStart("1");
        vipCard.setIsShow("1");
        QueryWrapper<CuVipCard> queryWrapper = new QueryWrapper<>(vipCard);
        queryWrapper.orderByAsc("sort");
        list = super.list(queryWrapper);
        if (ObjectUtil.isEmpty(list)) {
            return null;
        }

        redisUtil.set(redlist, list, CommonCuckoo.CACHE_TIME);
        return list;
    }

    @Override
    public boolean save(CuVipCard vipCard) {
        redisUtil.del(redlist);
        return super.save(vipCard);
    }

    @Override
    public boolean updateById(CuVipCard vipCard) {
        redisUtil.del(redlist);
        redisUtil.del(key + vipCard.getId());
        return super.updateById(vipCard);
    }

    @Override
    public boolean removeById(String id) {
        redisUtil.del(redlist);
        redisUtil.del(key + id);
        return super.removeById(id);
    }

    @Override
    public boolean removeByIds(List<String> ids) {
        redisUtil.del(key);
        return super.removeByIds(ids);
    }

    @Override
    public CuVipCard getById(String id) {
        CuVipCard vipCard = (CuVipCard) redisUtil.get(key + id);

        if (ObjectUtil.isNotEmpty(vipCard)) {
            return vipCard;
        }

        vipCard = super.getById(id);
        if (ObjectUtil.isEmpty(vipCard)) {
            return null;
        }
        redisUtil.set(key + id, vipCard, CommonCuckoo.CACHE_TIME);
        return vipCard;
    }

    @Override
    public PaymentResponse buyVipCard(CuVipCard vipCard, CuUserDetails userDetails, String clientIp) {
        // 存储订单记录
        String orderId = GeneralToolsUtil.generateOrderId();
        String note = "【" + userDetails.getUserName() + "】购买会员卡【" + vipCard.getTitle() + "】";

        // 创建订单
        CuPaymentOrders paymentOrders = new CuPaymentOrders();
        paymentOrders.setUserId(userDetails.getId());
        paymentOrders.setOrderId(orderId);
        paymentOrders.setPaymentStatus(PaymentStatusEnum.PAYMEN_TSTATUS_PENDING);
        paymentOrders.setPaymentAmount(vipCard.getPrice());
        paymentOrders.setProductId(vipCard.getId());
        paymentOrders.setNote(note);

        // 调用支付接口
        // 下单 String outTradeNo, String name, BigDecimal money, String clientIp, PaymentPlatformEnum platformEnum, DeviceTypeEnum device
        PaymentUtil paymentUtil = new PaymentUtil(CuPaymentPlatformEnum.BMWLPLAT);
        PaymentResponse paymentResponse = paymentUtil.createOrder(orderId, vipCard.getTitle(), vipCard.getPrice(), clientIp, PaymentMethodEnum.PAYMENT_METHOD_WECHAT, CuDeviceTypeEnum.MOBILE.getCode());

        paymentOrders.setPaymentReference(paymentResponse.getTrade_no());
        if (ObjectUtil.isEmpty(paymentResponse) || paymentResponse.getCode() != 1) {
            return paymentResponse;
        }

        // 保存订单
        paymentOrders.setPaymentMethod(PaymentMethodEnum.PAYMENT_METHOD_ALIPAY);
        paymentOrders.setPaymentStatus(PaymentStatusEnum.PAYMEN_TSTATUS_PROCESSING);
        paymentOrdersService.save(paymentOrders);

        return paymentResponse;
    }

    @Override
    public boolean payResult(CuPaymentOrders cuPaymentOrders) {
        // 更新状态
        cuPaymentOrders.setPaymentStatus(PaymentStatusEnum.PAYMEN_TSTATUS_SUCCESS);
        cuPaymentOrders.setPaymentTime(new Date());

        // 查询卡卷
        CuVipCard vipCard = this.getById(cuPaymentOrders.getProductId());
        if (ObjectUtil.isEmpty(vipCard)) {
            return false;
        }

        // 获取支付用户信息
        CuUserDetails userDetails = userDetailsService.getById(cuPaymentOrders.getUserId());
        if (ObjectUtil.isEmpty(userDetails)) {
            return false;
        }

        // 给用户添加会员时间 判断当前用户是否是会员 会员结束时间是否大于当前时间
        if (userDetails.getEndVip().before(new Date())) {
            userDetails.setEndVip(new Date());
        }
        userDetails.setEndVip(DateUtil.offsetDay(userDetails.getEndVip(), vipCard.getDaysNumber()));
        userDetails.setIsVip(CommonCuckoo.IS_VIP);

        // 修改钱包
        String description = "购买优惠卷【" + vipCard.getTitle() + "】";
        // String userId, BigDecimal amount, String type, Integer start, String description, String otherId
        walletaMnagementService.updateWalletAmount(
                userDetails.getId(),
                cuPaymentOrders.getPaymentAmount(),
                TransactionTypeEnum.TRANSACTION_TYPE_EXCHANGE,
                TransactionStatusEnum.TRANSACTION_STATUS_CONFIRMED,
                vipCard.getId(),
                description);

        userDetailsService.updateById(userDetails);
        paymentOrdersService.updateById(cuPaymentOrders);

        // 提成计算
        walletaMnagementService.payReward(userDetails, cuPaymentOrders.getPaymentAmount());
        return true;
    }
}
